#include <Sieve.hpp>
#include <iostream>
#include <Trie.hpp>
#include <sstream>
#include <Utility.hpp>
#include <cstdlib>
#include <ctime>
#include <GTrie.hpp>
#include <mpi.h>

Sieve::Sieve(int rank, int np) : rank(rank), np(np) {
	// nothing
}

void Sieve::run() {

	int bsz;
	MPI::COMM_WORLD.Recv(&bsz, 1, MPI_INT, 0, MPI_ANY_TAG);

	char * buffer = new char[bsz];

	MPI::Status status;
	for (int st = 0; st < bsz; ) {
		MPI::COMM_WORLD.Recv(buffer, bsz,
			MPI_CHAR, 0, MPI_ANY_TAG, status);
		st += status.Get_count(MPI_CHAR);
	}

	std::stringstream ss;
	ss << buffer;
	delete buffer;

	Trie * trie = new Trie();
	int myqty = trie->deserialize(ss);

	std::cout << "Sieve " << rank << " received "
		<< myqty << " parts\n";

	for (int found = 0; found < myqty; ) {
		std::string word = Utility::randomWord(true);
		std::vector<std::string> search = 
			trie->retrieveUntil(word);
		if (search.size()) {
			found++;
			trie->remove(word);
		}
	}

	delete trie;

	std::cout << "Sieve " << rank << 
		" finished. Waiting for others\n";

	MPI::COMM_WORLD.Barrier();

}

